package com.fomky.queried.service.connect;

import com.fomky.queried.plugin.common.AbstractConnectPlugin;
import com.fomky.queried.plugin.common.ConnectConfig;
import com.fomky.queried.plugin.common.ConnectPlugin;
import com.google.common.collect.Maps;
import lombok.Builder;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.database.mysql.MySQLConnection;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.TimeZone;

@Slf4j
@Service
public class ConnectManager implements InitializingBean {


    private String basePackage = "com.fomky.queried";

    protected Map<String, ConnectPlugin> plugins = Maps.newHashMap();
    protected Map<String, Class<? extends ConnectPlugin>> pluginClassMap = Maps.newHashMap();

    public ConnectPlugin findAndCreateConnect(String connectId, String connect) {
        if (!plugins.containsKey(connectId)) {
            this.initConnectPlugin(connectId, connect);
        }
        return plugins.get(connectId);
    }

    @SneakyThrows
    private void initConnectPlugin(String connectId, String connect) {
        ConnectConfig config = this.queryConfig(connect);
        Class<? extends ConnectPlugin> pluginClass = pluginClassMap.get(connect);
        Constructor<? extends ConnectPlugin> constructor = pluginClass.getConstructor();
        ConnectPlugin plugin = constructor.newInstance().init(config);
        plugins.put(connectId, plugin);
    }

    private ConnectConfig queryConfig(String connect) {
        return ConnectConfig.builder()
                .host("127.0.0.1")
                .port(3306)
                .user("root")
                .password("12345678")
                .connectionTimeZone(TimeZone.getDefault().getID())
                .build();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("ConnectManager init. ...... ");
        ServiceLoader<ConnectPlugin> loader = ServiceLoader.load(ConnectPlugin.class);
        for (ConnectPlugin executor : loader) {
            pluginClassMap.put(executor.name(), executor.getClass());
        }
        if(pluginClassMap.isEmpty()) {
            log.warn(">>>>>>>>>>>>>>>> No Plugin found.... ");
        }
    }
}
